//
//  SimPhotoBrowser.m
//  SimPhotoBrowser
//

#import "SimPhotoBrowser.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <QuartzCore/QuartzCore.h>
#import "SDImageCache.h"
#import "UIAlertView+SimAdditions.h"
#import "UIImage+SimAdditions.h"
#import "UIBarButtonItem+SimAdditions.h"
#import "UIButton+SimAdditions.h"
#import "SimAlertView.h"
#import "SimActionSheet.h"
#import "SimZoomImagelView.h"
#import "SimGesturePopNavVC.h"
#import "UIView+SimAdditions.h"
#import "UIViewController+SimAddition.h"
#import "SimLoading.h"
#import "SimImageEditorVC.h"
#import "SimImageEditModel.h"

SimImpValue(kSimPhotoBrowserFinishSelectColor, UIColor *)

SimImpValue(kSimPhotoBrowserUnSelectedIcon, NSString *)
SimImpValue(kSimPhotoBrowserSelectedIcon, NSString *)

SimImpValue(kSimPhotoBrowserEditIcon, NSString *)
SimImpValue(kSimPhotoBrowserDeleteIcon, NSString *)

#define PADDING                  10

@interface SimPhotoBrowser () <UIActionSheetDelegate>
{
    BOOL _bShowControl;
    BOOL _hasChanged;
    
    // Data
    NSMutableArray *_photoModels;
    
    // Views
    UIScrollView *_pagingScrollView;
    
    //Delete
    UIButton *_deleteBtn;
    
    //Edit
    UIButton *_editBtn;
    
    //Select
    UIToolbar *_toolbar;
    UIButton *_selectFinishBtn;
    UIButton *_selectNavbarItemBtn;
    
    // Paging & layout
    NSMutableArray *_visiblePages;
    NSUInteger _previousPageIndex;
    CGRect _previousLayoutBounds;
    NSUInteger _pageIndexBeforeRotation;
    
    // Appearance
    BOOL _previousNavBarHidden;
    BOOL _previousNavBarTranslucent;
    UIBarStyle _previousNavBarStyle;
    UIStatusBarStyle _previousStatusBarStyle;
    UIColor *_previousNavBarTintColor;
    UIColor *_previousNavBarBarTintColor;
    UIBarButtonItem *_previousViewControllerBackButton;
    UIImage *_previousNavigationBarBackgroundImageDefault;
    UIImage *_previousNavigationBarBackgroundImageLandscapePhone;
    
    BOOL _didSavePreviousStateOfNavBar;
    BOOL _viewHasAppearedInitially;
    CGPoint _currentGridContentOffset;
    
    
}
@property (nonatomic, assign) NSInteger deleteIndex;

@end

@implementation SimPhotoBrowser

- (id)init
{
    if ((self = [super init])) {
        self.hidesBottomBarWhenPushed = YES;
        if (!ABOVE_IOS7) {
            self.wantsFullScreenLayout = YES;
        }
        _enableSave = YES;
        _hasChanged = NO;
        _previousLayoutBounds = CGRectZero;
        _currentPageIndex = 0;
        _previousPageIndex = NSUIntegerMax;
        _visiblePages = [[NSMutableArray alloc] init];
        _photoModels = nil;
        _currentGridContentOffset = CGPointMake(0, CGFLOAT_MAX);
        _didSavePreviousStateOfNavBar = NO;
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handlephotoLoadFinishNoti:)
                                                     name:kSimPhotoModelImageLoadFinishNoti
                                                   object:nil];
    }
    return self;
}


- (id)initWithImageContents:(NSArray *)imageContents index:(NSInteger)index
{
    if ((self = [self init])) {
        if (!ABOVE_IOS7) {
            self.wantsFullScreenLayout = YES;
        }
        _deleteIndex = NSNotFound;
        _imageContents = [NSMutableArray arrayWithArray:imageContents];
        [self setCurrentPhotoIndex:index];
    }
    return self;
}

- (void)dealloc {
    NSLog(@"dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _pagingScrollView.delegate = nil;
    [[SDImageCache sharedImageCache] clearMemory]; // clear memory
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - View Loading
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]){
        [self setEdgesForExtendedLayout:UIRectEdgeAll];
    }
    self.view.backgroundColor = HEXRGBCOLOR(0x000000);
    self.view.clipsToBounds = YES;
    
    // Setup paging scrolling view
    CGRect pagingScrollViewFrame = [self frameForPagingScrollView];
    _pagingScrollView = [[UIScrollView alloc] initWithFrame:pagingScrollViewFrame];
    _pagingScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _pagingScrollView.pagingEnabled = YES;
    _pagingScrollView.delegate = self;
    _pagingScrollView.showsHorizontalScrollIndicator = NO;
    _pagingScrollView.showsVerticalScrollIndicator = NO;
    _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    [self.view addSubview:_pagingScrollView];
    
    if ([self.navigationController.viewControllers firstObject] != self) {
        [self addBackItem];
    }
    
    if (_enableDelete){
        NSString *deleteIcon = SimValue(kSimPhotoBrowserDeleteIcon, @"icon_browser_delete");
        _deleteBtn = [UIButton btnWithImageNames:@[deleteIcon] btnSize:CGSizeMake(50, 50)];
        [_deleteBtn addTarget:self action:@selector(clickDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_deleteBtn];
        [self updateEditBtnPosition];
    }
    
    if (_enableEdit) {
        NSString *editCion = SimValue(kSimPhotoBrowserEditIcon, @"icon_browser_edit");
        _editBtn = [UIButton btnWithImageNames:@[editCion] btnSize:CGSizeMake(50, 50)];
        [_editBtn addTarget:self action:@selector(clickEditBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_editBtn];
        [self updateEditBtnPosition];
    }
    
    if (_enableSelect) {
        [self showControls:YES animated:NO];
        
        _toolbar = [[UIToolbar alloc] initWithFrame:[self frameForToolbarAtOrientation:self.interfaceOrientation]];
        _toolbar.tintColor = ABOVE_IOS7 ? [UIColor whiteColor] : nil;
        if ([_toolbar respondsToSelector:@selector(setBarTintColor:)]) {
            _toolbar.barTintColor = nil;
        }
        if ([[UIToolbar class] respondsToSelector:@selector(appearance)]) {
            [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
            [_toolbar setBackgroundImage:nil forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsLandscapePhone];
        }
        _toolbar.barStyle = UIBarStyleBlackTranslucent;
        _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
        _toolbar.backgroundColor = HEXRGBCOLOR(0x373737);
        for (UIView *view in [_toolbar subviews]) {
            if ([view isKindOfClass:[UIImageView class]]) {
                [view removeFromSuperview];
            }
        }
        [self.view addSubview:_toolbar];
        
        UIBarButtonItem *flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        
        _selectFinishBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        _selectFinishBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_selectFinishBtn addTarget:self action:@selector(doFinishSelect) forControlEvents:UIControlEventTouchUpInside];
        [_selectFinishBtn setTitle:@"完成(9)" forState:UIControlStateNormal];
        [_selectFinishBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_selectFinishBtn setTitleColor:HEXRGBCOLOR(0x999999) forState:UIControlStateDisabled];
        [_selectFinishBtn setBackgroundImage:[UIImage imageWithColor:SimValue(kSimPhotoBrowserFinishSelectColor, HEXRGBCOLOR(0x46b789))]
                                    forState:UIControlStateNormal];
        [_selectFinishBtn setBackgroundImage:[UIImage imageWithColor:HEXRGBCOLOR(0xe7e7e7)]
                                    forState:UIControlStateDisabled];
        
        _selectFinishBtn.layer.cornerRadius = 2;
        _selectFinishBtn.layer.masksToBounds = YES;
        [_selectFinishBtn sizeToFit];
        _selectFinishBtn.width += 10;
        _selectFinishBtn.height += 10;
        UIBarButtonItem *finishItem = [[UIBarButtonItem alloc] initWithCustomView:_selectFinishBtn];
        _toolbar.items = @[flexibleSpaceItem, finishItem];
        
        NSString *unSelectedImageStr = SimValue(kSimPhotoBrowserUnSelectedIcon, @"ImageSelectedOff");
        UIImage *selectedImage = SimUIImageNamed(SimValue(kSimPhotoBrowserSelectedIcon, @"ImageSelectedOn"));
        _selectNavbarItemBtn = [UIButton btnWithImageNames:@[unSelectedImageStr]];
        [_selectNavbarItemBtn setImage:selectedImage forState:UIControlStateSelected];
        [_selectNavbarItemBtn addTarget:self action:@selector(selecteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_selectNavbarItemBtn];
        
        [self.view addSubview:_toolbar];
    }
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    if (_photoModels == nil) {
        _photoModels = [NSMutableArray array];
        [self reloadData];
    }
    [self layoutVisiblePages];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.isMovingToParentViewController && [self.navigationController.viewControllers objectAtIndex:0] != self) {
        [self storePreviousNavBarAppearance];
    }
    [self setNavBarAppearance:YES];
    if(_enableSelect){
        [self updateSelectCount];
    }
    else{
        [self showControls:NO animated:NO];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self showControls:YES animated:NO];
    
    if (self.isMovingFromParentViewController && [self.navigationController.viewControllers objectAtIndex:0] != self) {
        [self restorePreviousNavBarAppearance:animated];
    }
    
    if (DEVICE_IS_IPHONE) {
        [[UIApplication sharedApplication] setStatusBarStyle:_previousStatusBarStyle animated:animated];
    }
}

#pragma mark -

- (void)updateEditBtnPosition
{
    _editBtn.bottom = _deleteBtn.bottom = self.view.height-20;
    if (_enableDelete && _enableEdit) {
        _deleteBtn.left = self.view.width/2 + 30;
        _editBtn.right = self.view.width/2 +- 30;
    }
    else if(_enableDelete){
        _deleteBtn.centerX = self.view.width/2;
    }
    else if(_enableEdit){
        _editBtn.centerX = self.view.width/2;
    }
}


- (void)performLayout
{
    [_visiblePages removeAllObjects];
    _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:_currentPageIndex];
    [self tilePages];
    
}

- (void)selecteBtnClick:(UIButton *)checkBtn
{
    BOOL shouldChange = YES;
    if (_selectedStatusChanged) {
        shouldChange = _selectedStatusChanged(self, _currentPageIndex, !checkBtn.selected);
    }
    if (shouldChange) {
        checkBtn.selected = !checkBtn.selected;
    }
    [self updateSelectCount];
}


- (void)doFinishSelect
{
    [self doQuitVC];
}

- (void)updateSelectCount
{
    NSInteger count = 0;
    if (_allSelectCount) {
        count = _allSelectCount(self);
    }
    
    if (count > 0){
        _selectFinishBtn.enabled = YES;
        [_selectFinishBtn setTitle:[NSString stringWithFormat:@"完成(%zd)", count] forState:UIControlStateNormal];
    } else {
        _selectFinishBtn.enabled = NO;
        [_selectFinishBtn setTitle:@"完成" forState:UIControlStateNormal];
    }
}

- (void)showEditBtns:(BOOL)show
{
    if (_enableDelete) {
        _deleteBtn.hidden = !show;
    }
    
    if (_enableEdit) {
        _editBtn.hidden = !show;
    }
}

#pragma mark - Notificaiton
- (void)handlephotoLoadFinishNoti:(NSNotification *)notification
{
    SimPhotoModel *photo = [notification object];
    SimZoomImagelView *page = [self pageDisplayingPhoto:photo];
    if (page) {
        if (photo.loadedImage != nil) {
            [self tryLoadSidePhotos:photo];
        }
    }
    
    if (page.index == _currentPageIndex) {
        [self showEditBtns:photo.loadedImage!=nil];
    }
}


- (void)storePreviousNavBarAppearance
{
    _didSavePreviousStateOfNavBar = YES;
    if ([UINavigationBar instancesRespondToSelector:@selector(barTintColor)]) {
        _previousNavBarBarTintColor = self.navigationController.navigationBar.barTintColor;
    }
    _previousNavBarTranslucent = self.navigationController.navigationBar.translucent;
    _previousNavBarTintColor = self.navigationController.navigationBar.tintColor;
    _previousNavBarHidden = self.navigationController.navigationBarHidden;
    _previousNavBarStyle = self.navigationController.navigationBar.barStyle;
    if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
        _previousNavigationBarBackgroundImageDefault = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsDefault];
        _previousNavigationBarBackgroundImageLandscapePhone = [self.navigationController.navigationBar backgroundImageForBarMetrics:UIBarMetricsLandscapePhone];
    }
}

- (void)restorePreviousNavBarAppearance:(BOOL)animated
{
    if (_didSavePreviousStateOfNavBar) {
        [self.navigationController setNavigationBarHidden:_previousNavBarHidden animated:animated];
        UINavigationBar *navBar = self.navigationController.navigationBar;
        navBar.tintColor = _previousNavBarTintColor;
        navBar.translucent = _previousNavBarTranslucent;
        if ([UINavigationBar instancesRespondToSelector:@selector(barTintColor)]) {
            navBar.barTintColor = _previousNavBarBarTintColor;
        }
        navBar.barStyle = _previousNavBarStyle;
        if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
            [navBar setBackgroundImage:_previousNavigationBarBackgroundImageDefault forBarMetrics:UIBarMetricsDefault];
            [navBar setBackgroundImage:_previousNavigationBarBackgroundImageLandscapePhone forBarMetrics:UIBarMetricsLandscapePhone];
        }
        // Restore back button if we need to
        if (_previousViewControllerBackButton) {
            UIViewController *previousViewController = [self.navigationController topViewController]; // We've disappeared so previous is now top
            previousViewController.navigationItem.backBarButtonItem = _previousViewControllerBackButton;
            _previousViewControllerBackButton = nil;
        }
    }
}

#pragma mark - Gesture
- (void)singleTapOnImageView
{
    if (_enableSelect) {
        [self showControls:!_bShowControl animated:YES];
    }
    else{
        [self doQuitVC];
    }
}

- (void)longOnImageView:(SimZoomImagelView *)imageView
{
    SimPhotoModel *photo = imageView.photo;
    if (_enableSave && photo.loadedImage != nil) {
        SimActionSheet *sheet = [[SimActionSheet alloc] initWithTitle:nil];
        sheet.totalBtnCount = ^{
            return 1;
        };
        sheet.btnTitleForIndex = ^(NSInteger index){
            switch (index) {
                case 0:
                    return @"保存到相册";
            }
            return @"取消";
        };
        sheet.clickOnIndex = ^(NSInteger index){
            switch (index) {
                case 0:{
                    UIImageWriteToSavedPhotosAlbum(photo.loadedImage,
                                                   self,
                                                   @selector(image:didFinishSavingWithError:contextInfo:), nil);
                }
                    break;
            }
        };
        
        [sheet showInView:self.view.window];

    }
}

#pragma mark - Layout

- (void)layoutVisiblePages
{
    // Adjust frames and configuration of each visible page
    for (SimZoomImagelView *page in _visiblePages) {
        NSUInteger index = page.index;
        page.frame = [self frameForPageAtIndex:index];
        if (!CGRectEqualToRect(_previousLayoutBounds, self.view.bounds)) {
            [page setMaxMinZoomScalesForCurrentBounds];
            _previousLayoutBounds = self.view.bounds;
        }
    }
    
    NSUInteger indexPriorToLayout = _currentPageIndex;
    _pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    _pagingScrollView.contentOffset = [self contentOffsetForPageAtIndex:indexPriorToLayout];
    [self willShowPageAtIndex:_currentPageIndex];
    _currentPageIndex = indexPriorToLayout;
}

- (void)reloadData {
    // Reset
    NSUInteger numberOfPhotos = _imageContents.count;
    [_photoModels removeAllObjects];
    for (int i = 0; i < numberOfPhotos; i++) {
        [_photoModels addObject:[NSNull null]];
    }
    
    // Update current page index
    if (numberOfPhotos > 0) {
        _currentPageIndex = MAX(0, MIN(_currentPageIndex, numberOfPhotos - 1));
    } else {
        _currentPageIndex = 0;
    }
    
    // Update layout
    if ([self isViewLoaded]) {
        while (_pagingScrollView.subviews.count) {
            [[_pagingScrollView.subviews lastObject] removeFromSuperview];
        }
        [self performLayout];
        [self.view setNeedsLayout];
    }
    
}

- (BOOL)photoIsSelectedAtIndex:(NSUInteger)index
{
    if (_enableSelect) {
        if (_isSelectedForIndex) {
            return _isSelectedForIndex(self, index);
        }
    }
    return NO;
}

- (BOOL)setPhotoSelected:(BOOL)selected atIndex:(NSUInteger)index
{
    if (_enableSelect) {
        if (_selectedStatusChanged) {
            _selectedStatusChanged(self, index, selected);
        }
    }
    
    return YES;
}

- (SimPhotoModel *)photoAtIndex:(NSUInteger)index
{
    SimPhotoModel * photo = nil;
    if (index < _photoModels.count) {
        if ([_photoModels objectAtIndex:index] == [NSNull null]) {
            if (index < _imageContents.count) {
                id imageInfo = _imageContents[index];
                if ([imageInfo isKindOfClass:[SimPhotoModel class]]) {
                    photo = imageInfo;
                }
                else if ([imageInfo isKindOfClass:[UIImageView class]]) {
                    photo = [SimPhotoModel photoWithImage:[(UIImageView *)imageInfo image]];
                }
                else if([imageInfo isKindOfClass:[NSString class]]){
                    NSString *filePath = (NSString *)imageInfo;
                    NSURL *url = nil;
                    url = [NSURL URLWithString:filePath];
                    if(url){
                        photo = [SimPhotoModel photoWithURL:url];
                    }
                }
                else if ([imageInfo isKindOfClass:[UIImage class]]) {
                    photo = [SimPhotoModel photoWithImage:imageInfo];
                }
                else if ([imageInfo isKindOfClass:[ALAsset class]]){
                    ALAssetRepresentation *rep = [(ALAsset *)imageInfo defaultRepresentation];
                    photo = [SimPhotoModel photoWithURL:[rep url]];
                }
                else if([imageInfo isKindOfClass:[SimImageEditModel class]]){
                    photo = [SimPhotoModel photoWithImage:[(SimImageEditModel *)imageInfo processImage]];
                }
            }
            if (photo){
                [_photoModels replaceObjectAtIndex:index withObject:photo];
            }
        } else {
            photo = [_photoModels objectAtIndex:index];
        }
    }
    return photo;
}

- (void)tilePages {
    
    // Calculate which pages should be visible
    // Ignore padding as paging bounces encroach on that
    // and lead to false page loads
    CGRect visibleBounds = _pagingScrollView.bounds;
    NSInteger iFirstIndex = (NSInteger)floorf((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds));
    NSInteger iLastIndex  = (NSInteger)floorf((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds));
    iFirstIndex = Range(iFirstIndex, 0, _imageContents.count-1);
    iLastIndex = Range(iLastIndex, 0, _imageContents.count-1);
    NSLog(@"iFirstIndex:%zd, iLastIndex:%zd", iFirstIndex, iLastIndex);
    
    // Recycle no longer needed pages
    NSInteger pageIndex;
    NSMutableArray *removePages = [NSMutableArray array];
    for (SimZoomImagelView *page in _visiblePages) {
        pageIndex = page.index;
        if (pageIndex < (NSUInteger)iFirstIndex || pageIndex > (NSUInteger)iLastIndex) {
            [page removeFromSuperview];
            [removePages addObject:page];
        }
    }
    [_visiblePages removeObjectsInArray:removePages];
    
    // Add missing pages
    for (NSUInteger index = (NSUInteger)iFirstIndex; index <= (NSUInteger)iLastIndex; index++) {
        if (![self isDisplayingPageForIndex:index]) {
            SimZoomImagelView *page = [[SimZoomImagelView alloc] initWithPhotoBrowser:self];
            page.zoomScrollViewBgColor = self.zoomScrollViewBgColor;
            DefineWeak(self);
            page.singlTap = ^(SimZoomImagelView *scrollview, id sender){
                [Weak(self) singleTapOnImageView];
            };
            page.longPress = ^(SimZoomImagelView *scrollview, id sender){
                [Weak(self) longOnImageView:scrollview];
            };

            
            [_visiblePages addObject:page];//should before page.photo = xx;
            page.frame = [self frameForPageAtIndex:index];
            page.index = index;
            page.photo = [self photoAtIndex:index];
            [_pagingScrollView addSubview:page];
        }
    }
    
}

- (void)reloadCurrentPage
{
    SimZoomImagelView *page = [self pageDisplayedAtIndex:_currentPageIndex];
    [_photoModels replaceObjectAtIndex:_currentPageIndex withObject:[NSNull null]];
    page.photo = [self photoAtIndex:_currentPageIndex];
}

- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
    for (SimZoomImagelView *page in _visiblePages){
        if (page.index == index) {
            return YES;
        }
    }
    return NO;
}

- (SimZoomImagelView *)pageDisplayedAtIndex:(NSUInteger)index {
    SimZoomImagelView *thePage = nil;
    for (SimZoomImagelView *page in _visiblePages) {
        if (page.index == index) {
            thePage = page;
            break;
        }
    }
    return thePage;
}

- (SimZoomImagelView *)pageDisplayingPhoto:(SimPhotoModel *)photo {
    SimZoomImagelView *thePage = nil;
    for (SimZoomImagelView *page in _visiblePages) {
        if (page.photo == photo) {
            thePage = page;
            break;
        }
    }
    return thePage;
}


- (void)willShowPageAtIndex:(NSUInteger)index
{
    if (_imageContents.count == 0) {
        [self showEditBtns:NO];
        return;
    }
    
    // Release images further away than +/-1
    for (int i = 0; i < _imageContents.count - 1; i++) {
        if(index == 0 || (i >= index - 1 && i <= index + 1)){
            continue;
        }
        SimPhotoModel *photo = [_photoModels objectAtIndex:i];
        if (![photo isKindOfClass:[NSNull class]]) {
            [photo unloadImage];
            [_photoModels replaceObjectAtIndex:i withObject:[NSNull null]];
        }
    }
    
    if (_enableSelect) {
        if (_isSelectedForIndex) {
            _selectNavbarItemBtn.selected = _isSelectedForIndex(self, index);
        }
        else{
            _selectNavbarItemBtn.selected = NO;
        }
    }
    
    if (_willShowPageIndex) {
        _willShowPageIndex(self, index);
    }
    
    SimPhotoModel * currentPhoto = [self photoAtIndex:index];
    if (currentPhoto.loadedImage != nil) {
        [self tryLoadSidePhotos:currentPhoto];
    }
    if (index != _previousPageIndex) {
        _previousPageIndex = index;
    }
    
    [self showEditBtns:currentPhoto.loadedImage!=nil];
}

- (void)tryLoadSidePhotos:(SimPhotoModel *)photo
{
    SimZoomImagelView *page = [self pageDisplayingPhoto:photo];
    if (page) {
        //Load images +/-1
        for (NSUInteger i = page.index-1; i < page.index+1; i++) {
            if (i < _imageContents.count - 1) {
                SimPhotoModel * photo = [self photoAtIndex:i];
                if (photo.loadedImage == nil) {
                    [photo tryLoadImage];
                }
            }
        }
    }
}


#pragma mark - Frame Calculations

- (CGRect)frameForPagingScrollView {
    CGRect frame = self.view.bounds;// [[UIScreen mainScreen] bounds];
    frame.origin.x -= PADDING;
    frame.size.width += (2 * PADDING);
    return CGRectIntegral(frame);
}

- (CGRect)frameForPageAtIndex:(NSUInteger)index {
    // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in
    // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's
    // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape
    // because it has a rotation transform applied.
    CGRect bounds = _pagingScrollView.bounds;
    CGRect pageFrame = bounds;
    pageFrame.size.width -= (2 * PADDING);
    pageFrame.origin.x = (bounds.size.width * index) + PADDING;
    return CGRectIntegral(pageFrame);
}

- (CGSize)contentSizeForPagingScrollView {
    // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
    CGRect bounds = _pagingScrollView.bounds;
    return CGSizeMake(bounds.size.width * _imageContents.count, bounds.size.height);
}

- (CGPoint)contentOffsetForPageAtIndex:(NSUInteger)index {
    CGFloat pageWidth = _pagingScrollView.bounds.size.width;
    CGFloat newOffset = index * pageWidth;
    return CGPointMake(newOffset, 0);
}

- (CGRect)frameForToolbarAtOrientation:(UIInterfaceOrientation)orientation {
    CGFloat height = 44;
    if (DEVICE_IS_IPHONE && UIInterfaceOrientationIsLandscape(orientation)) height = 32;
    return CGRectIntegral(CGRectMake(0, self.view.bounds.size.height - height, self.view.bounds.size.width, height));
}
#pragma mark - UIScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.bViewAppear){
        return;
    }
    
    [self tilePages];
    CGRect visibleBounds = _pagingScrollView.bounds;
    NSInteger index = (NSInteger)(floorf(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds)));
    index = Range(index, 0, (_imageContents.count - 1));
    if (_currentPageIndex != index) {
        _currentPageIndex = index;
        [self willShowPageAtIndex:index];
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (_deleteIndex != NSNotFound) {
        [self deletePhotoAtIndex:_deleteIndex];
        NSInteger tempIndex = _currentPageIndex;
        if (_currentPageIndex > _deleteIndex) {
            tempIndex -= 1;
            [self reloadData];
            [self setCurrentPhotoIndex:tempIndex];
        }
        else{
            [self reloadData];
        }
        _deleteIndex = NSNotFound;
        
    }
}

- (void)jumpToPageAtIndex:(NSUInteger)index animated:(BOOL)animated
{
    if (index < _imageContents.count) {
        CGRect pageFrame = [self frameForPageAtIndex:index];
        [_pagingScrollView setContentOffset:CGPointMake(pageFrame.origin.x - PADDING, 0) animated:animated];
    }
}

- (void)gotoPreviousPage
{
    [self showPreviousPhotoAnimated:NO];
}

- (void)gotoNextPage
{
    [self showNextPhotoAnimated:NO];
}

- (void)showPreviousPhotoAnimated:(BOOL)animated
{
    [self jumpToPageAtIndex:_currentPageIndex-1 animated:animated];
}

- (void)showNextPhotoAnimated:(BOOL)animated
{
    [self jumpToPageAtIndex:_currentPageIndex+1 animated:animated];
}

#pragma mark - NavBarAppearance

- (void)setNavBarAppearance:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.tintColor = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7") ? [UIColor whiteColor] : nil;
    if ([navBar respondsToSelector:@selector(setBarTintColor:)]) {
        navBar.barTintColor = nil;
        UIImage *blankImage = [[UIImage alloc] init];
        navBar.shadowImage = blankImage;
    }
    navBar.translucent = YES;
    navBar.barStyle = UIBarStyleBlackTranslucent;
    if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) {
        UIImage *bgImage = [UIImage imageWithColor:HEXRGBCOLOR(0x373737)];
        [navBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
        [navBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsLandscapePhone];
    }
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        _previousStatusBarStyle = [[UIApplication sharedApplication] statusBarStyle];
        if (ABOVE_IOS7) {
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:animated];
        } else {
            [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:animated];
        }
    }
}

- (void)showControls:(BOOL)show animated:(BOOL)animated
{
    if (_imageContents.count == 0 ){
        show = YES;
    }
    _bShowControl = show;
    
    CGFloat animationDuration = (animated ? 0.35 : 0);
    [[UIApplication sharedApplication] setStatusBarHidden:!show withAnimation:animated ? UIStatusBarAnimationSlide : UIStatusBarAnimationNone];
    CGRect navBarFrame = self.navigationController.navigationBar.frame;
    if (show) {
        navBarFrame.origin.y = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
    }
    else{
        navBarFrame.origin.y = -1*CGRectGetHeight(navBarFrame);
    }
    CGRect toolBarFrame = CGRectOffset([self frameForToolbarAtOrientation:self.interfaceOrientation], 0, show ? 0 : CGRectGetHeight(_toolbar.frame));
    [UIView animateWithDuration:animationDuration
                          delay:0.0f
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^(void) {
                         [self.navigationController.navigationBar setAlpha:(show ? 1.0f : 0.0f)];
                         
                         self.navigationController.navigationBar.frame = navBarFrame;
                         _toolbar.frame = toolBarFrame;
                     } completion:^(BOOL finished) {
                         [self.navigationController setNavigationBarHidden:!show animated:NO];
                     }];
}

#pragma mark - Properties
- (void)setInitialPageIndex:(NSUInteger)index
{
    [self setCurrentPhotoIndex:index];
}

- (void)setCurrentPhotoIndex:(NSUInteger)index
{
    NSUInteger photoCount = _imageContents.count;
    _currentPageIndex = MIN(photoCount-1, MAX(0, index));
    
    if ([self isViewLoaded]) {
        [self jumpToPageAtIndex:index animated:NO];
        if (self.bViewAppear){
            [self tilePages];
        }
    }
}



#pragma mark - Delete Edit Method


- (void)clickDeleteBtn
{
    SimAlertView *alertView = [[SimAlertView alloc] initWithTitle:@"删除" message:@"确认要删除这张图片吗?" btns:@[@"取消", @"确认"] dismissBlock:^(NSInteger selectedIndex) {
        if (selectedIndex == 1) {
            [self deletePhoto];
        }
    }];
    [alertView show];
}

- (void)deletePhoto
{
    SimPhotoModel * photo = [self photoAtIndex:_currentPageIndex];
    NSInteger photoCount = _imageContents.count;
    if (photoCount == 0) {
        [self doQuitVC];
    }
    else{
        if (photo.loadedImage != nil) {
            if (_currentPageIndex < _imageContents.count) {
                if(_imageContents.count == 1){
                    [self deletePhotoAtIndex:0];
                    [self doQuitVC];
                }
                else{
                    self.deleteIndex = _currentPageIndex;
                    if (_currentPageIndex < _imageContents.count-1) { //不是最后一个
                        [self showNextPhotoAnimated:YES];
                    }
                    else{
                        [self showPreviousPhotoAnimated:YES];
                    }
                }
            }
        }
    }
}

- (void)clickEditBtn
{
    SimPhotoModel * photo = [self photoAtIndex:_currentPageIndex];
    if (photo.loadedImage != nil) {
        SimImageEditModel *editModel = _imageContents[_currentPageIndex];
        if ([editModel isKindOfClass:SimImageEditModel.class]) {
            SimImageEditorVC *editVC = [[SimImageEditorVC alloc] initWithEditModel:editModel];
            editVC.finishEdit = ^(SimImageEditorVC *vc, BOOL hasChange){
                if (hasChange) {
                    _hasChanged = YES;
                    [editModel tryUpdateEditStatus];
                    [self reloadCurrentPage];
                }
            };
            
            SimGesturePopNavVC *navc = [[SimGesturePopNavVC alloc] initWithRootViewController:editVC];
            [self presentViewController:navc animated:YES completion:nil];
        }
    }
}


- (void)doQuitVC
{
    if (self.didFinishBrowser) {
        self.didFinishBrowser(self, _hasChanged);
    }
    if (self.navigationController.viewControllers.count > 1) {
        [self doPopBack];
    }
    else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}



- (void)deletePhotoAtIndex:(NSInteger)index
{
    if (index < _imageContents.count) {
        _hasChanged = YES;

        if (_enableEdit) {
            SimImageEditModel *editModel = _imageContents[index];
            [editModel cleanup];
        }
        [_imageContents removeObjectAtIndex:index];
        [self reloadData];
    }
}

#pragma mark - 保存图片
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    [SimLoading showLoadingType:LT_Success content:error ? @"保存失败" : @"已保存到相册"];
}

@end
